﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;

/// <summary>
///BasePage 的摘要说明
/// </summary>
public class BasePage : System.Web.UI.Page
{
    public BasePage()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    protected override void OnInit(EventArgs e)
    {
        if (Session["user"] == null)
        {
            if (Request["openid"] != null)
            {
                string user = EasyTool.Request("http://grazesheep.be-xx.com/api/oauth2/userinfo", "GET", "openid=" + Request["openid"] + "&key=" + Request["key"]);
                Json u = new Json(user);
                if (u["errcode"] == null)
                {
                    Session["user"] = user;
                }
                else
                {
                    EasyTool.Log(user);
                }
            }
            else
            {
                Response.Redirect("http://grazesheep.be-xx.com/api/oauth2/authorize?key=03am3n7ti3r9sewu&path=" + Uri.EscapeDataString(Request.RawUrl.Remove(0, 1)) + "&scope=snsapi_userinfo");
            }
        }
    }

    public string GetLang()
    {
        return Request.Url.AbsolutePath.Split('/')[1];
    }

    public void Alert(string str)
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "onload", "<script type=\"text/javascript\" language=\"javascript\">alert(\"" + str + "\");</script>");
    }

    public void AlertRedirect(string str, string url)
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "onload", "<script type=\"text/javascript\" language=\"javascript\">alert(\"" + str + "\");location.href='" + url + "';</script>");
    }

    public void ExecutionScript(string js)
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "onload", "<script type=\"text/javascript\" language=\"javascript\">" + js + "</script>");
    }

    public void ConfirmRedirect(string str, string url)
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "onload", "<script type=\"text/javascript\" language=\"javascript\">if(confirm('" + str + "')){location.href='" + url + "';}else{return false;}</script>");
    }

    public static string ToJson(DataTable dt, string jsonName)
    {
        StringBuilder Json = new StringBuilder();
        if (string.IsNullOrEmpty(jsonName))
            jsonName = dt.TableName;
        Json.Append("[");
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Json.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString().Replace("\"", "'") + "\"");
                    if (j < dt.Columns.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < dt.Rows.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]");
        return Json.ToString();

    }

    /// <summary>
    /// 字符串过滤：空格,双引号和换行符
    /// </summary>
    /// <param name="str">传入string</param>
    /// <returns>新string</returns>
    public static string StringDispose(string str)
    {
        if (str == null || str.Length < 1) { return ""; }
        string strs = str.Replace(" ", "");
        strs = strs.Replace("'", "");
        strs = strs.Replace("\"", "");
        strs = strs.Replace("\n", "");
        strs = strs.Replace("\t", "");
        strs = strs.Replace("\r", "");
        strs = strs.Replace("\r\n", "");
        strs = strs.Replace(Environment.NewLine.ToString(), "");
        return strs;
    }

    public static string EncodeStr(string str)
    {
        str = str.Replace("'", "’");
        str = str.Replace("\"", "&quot;");
        str = str.Replace("<", "&lt;");
        str = str.Replace(">", "&gt;");
        str = str.Replace("<br>", "\n");
        return str;
    }

    public static string EncodeString(string html)
    {
        System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        html = regex5.Replace(html, ""); //过滤frameset 
        html = regex6.Replace(html, ""); //过滤frameset 
        html = regex7.Replace(html, ""); //过滤frameset 
        html = regex8.Replace(html, ""); //过滤frameset 
        html = regex9.Replace(html, "");
        html = html.Replace(" ", "");
        html = html.Replace("</strong>", "");
        html = html.Replace("<strong>", "");
        return html;
    }

    protected string UpLoadImg(FileUpload file, string path)
    {
        if (file.PostedFile.ContentLength > 0)
        {
            string name = file.FileName;
            int size = file.PostedFile.ContentLength;
            string type = file.PostedFile.ContentType;
            string ipath = Server.MapPath(path) + name;
            if (type.Contains("image"))
            {
                // 1MB
                if (size < 1048576)
                {
                    file.SaveAs(ipath);
                    return name;
                }
                else
                    return "0";
            }
            else
                return "0";
        }
        else
        {
            return "";
        }
    }

    /// <summary>
    /// 上传文件公共方法
    /// </summary>
    /// <param name="file"></param>
    /// <param name="path"></param>
    /// <param name="filetype"></param>
    /// <returns></returns>
    protected string UploadFile(FileUpload file, string path, string filetype)
    {
        if (file.PostedFile.ContentLength > 0)
        {
            string name = file.FileName;
            int size = file.PostedFile.ContentLength;
            string type = file.PostedFile.ContentType;
            string ipath = Server.MapPath(path) + name;
            if (type.Contains("application/pdf"))
            {
                file.SaveAs(ipath);
                return name;
            }
            else
                return "0";
        }
        else
        {
            return "";
        }
    }

    /// <summary>
    /// 解析字符串,Json格式:[{"key":"value","key":"value"}]或[{"key":"value","key":"value"},{"key":"value","key":"value""}]
    /// </summary>
    /// <param name="JsonStr">传入Json字符串</param>
    /// <returns>返回DataTable</returns>
    public static DataTable GetDataTableByJosn(string JsonStr)
    {
        StringBuilder sb = new StringBuilder(StringDispose(JsonStr.Trim()));
        sb.Remove(0, 1);
        sb.Remove(sb.Length - 1, 1);
        string strs = sb.ToString();

        string[] strArrA = strs.Replace("},{", "}{").Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries);

        if (strArrA == null || strArrA.Length < 1) { return new DataTable(); }

        DataTable dt = new DataTable("TableA");
        bool ckA = true;
        foreach (string strA in strArrA)
        {
            string[] strArrB = strA.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (ckA)
            {
                foreach (string strB in strArrB)
                {
                    string[] strArrC = strB.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    dt.Columns.Add(strArrC[0], typeof(string));
                }
                ckA = false;
            }
        }
        foreach (string strA in strArrA)
        {
            DataRow drAll = dt.NewRow();
            string[] strArrB = strA.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string strB in strArrB)
            {
                string[] strArrC = strB.Split(':');
                drAll[strArrC[0]] += strArrC[1];
            }
            dt.Rows.Add(drAll);
        }

        return dt;
    }

}